import time
import os

import Pyro.core
import statgrab 

class AstmonHostStats(Pyro.core.ObjBase):
    lastStatsUpdate = 0

    def __init__(self, asteriskbin):
        Pyro.core.ObjBase.__init__(self)
        self.asteriskbin = asteriskbin
        if self.__checkAstVersion() == "1.4":
            self.coreshowchannels = "core show channels"
            self.coreshowuptime = "core show uptime"
        else:
            self.coreshowchannels = "show channels"
            self.coreshowuptime = "show uptime"
        self.__updateStats()

    def __updateStats(self):
        # update stats every 15 seconds.
        if time.time() - self.lastStatsUpdate > 3:
            self.lastStatsUpdate = time.time()
            self.diskUsage = statgrab.sg_get_fs_stats()
            self.loadStats = statgrab.sg_get_load_stats()
            self.cpuPercents = statgrab.sg_get_cpu_percents()
            self.memStats = statgrab.sg_get_mem_stats()
            self.swapStats = statgrab.sg_get_swap_stats()
            self.sysUptime = statgrab.sg_get_host_info()
            self.processCount = statgrab.sg_get_process_count()
            self.astchannels = self.__readAstChannels()
            self.astcalls = self.__readAstCalls()
            self.astuptime = self.__readAstUptime()

    def __checkAstVersion(self):
        result = os.popen(self.asteriskbin + " -rx \"core show version\" |grep Asterisk", "r").read()
        if result.find("Asterisk") != -1:
            return "1.4" # 1.4 or greater
        else:
            return "1.2"

    def __readAstChannels(self):
        result = os.popen(self.asteriskbin + " -rx \""+self.coreshowchannels+"\" | grep \"active channel\"", "r").read()
        try:
            numchannels = int(result[:result.find(" ")].strip())
        except ValueError:
            return -1
        return numchannels

    def __readAstCalls(self):
        result = os.popen(self.asteriskbin + " -rx \""+self.coreshowchannels+"\" | grep \"active calls\"", "r").read()
        try:
            numcalls = int(result[:result.find(" ")].strip())
	except ValueError:
            return -1
        return numcalls

    def __readAstUptime(self):
        result = os.popen(self.asteriskbin + " -rx \""+self.coreshowuptime+"\" | grep \"System uptime\"", "r").read()
        data = result.split(",")
        secs = 0
        for d in data:
            if d.find("hour") != -1: mult = 60*60
            elif d.find("minutes") != -1: mult = 60
            else: mult = 1
            d = d.replace("minutes", "").strip()
            d = d.replace("minute", "").strip()
            d = d.replace("seconds", "").strip()
            d = d.replace("second", "").strip()
            d = d.replace("hours", "").strip()
            d = d.replace("hour", "").strip()
            d = d.replace("System uptime:", "").strip()
            try:
                secs += int(d) * mult
            except ValueError:
                return 0
        return secs

    def getDiskUsage(self):
        self.__updateStats()
        return self.diskUsage 

    def getLoadStats(self):
        self.__updateStats()
        return self.loadStats

    def getCPUPercents(self):
        self.__updateStats()
        return self.cpuPercents

    def getMemStats(self):
        self.__updateStats()
        return self.memStats

    def getSwapStats(self):
        self.__updateStats()
        return self.swapStats

    def getSysUptime(self):
        self.__updateStats()
        return self.sysUptime

    def getProcessCount(self):
        self.__updateStats()
        return self.processCount

    def getAstChannels(self):
        self.__updateStats()
        return self.astchannels

    def getAstCalls(self):
        self.__updateStats()
        return self.astcalls

    def getAstUptime(self):
        self.__updateStats()
        return self.astuptime
